package com.itheima.reggie.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.crypto.SecureUtil;
import com.itheima.reggie.common.EmployeeUtil;
import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.domain.Employee;
import com.itheima.reggie.mapper.EmployeeMapper;
import com.itheima.reggie.service.EmployeeService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;

@Service
@Transactional
public class EmployeeServiceImpl implements EmployeeService {
	@Autowired
	private EmployeeMapper employeeMapper;
	
	@Autowired
	private HttpSession session;
	
	@Override
	public ResultInfo login(String username, String password) {
		//从数据库中查询用户
		Employee employee = employeeMapper.findByUsername(username);

		//判断结果是否为空
		if (employee == null) {
			return ResultInfo.error("用户不存在");
		}
		//如果用户不为空则对比密码
		String passwordWithMd5 = SecureUtil.md5(password);
		if (!StringUtils.equals(passwordWithMd5,employee.getPassword())) {
			return ResultInfo.error("密码错误");
		}
		
		//如果密码也正确,则查看用户状态是否被禁用
		if (employee.getStatus() == Employee.STATUS_DISABLE) {
			return ResultInfo.error("当前用户已被禁用");
		}
		
		return ResultInfo.success(employee);
	}
	
	@Override
	public void save(Employee employee) {
		//业务层
		//餐宿补齐
		
		//雪花算法补全id
		employee.setId(IdUtil.getSnowflake(1,1).nextId());
		
		//设置默认密码
		employee.setPassword(SecureUtil.md5("123"));
		
		//状态
		employee.setStatus(Employee.STATUS_ENABLE);
		
		// todo 日期设置,后期优化
		// employee.setCreateTime(new Date());
		// employee.setUpdateTime(new Date());
		//
		// todo 创建用户,需要从session中获取到当前操作用户
		// todo 测试是否从session中获取到了用户信息
		// Employee session_employee = (Employee)session.getAttribute("SESSION_EMPLOYEE");
		// employee.setCreateUser(EmployeeUtil.getNowUser(session).getId());
		//
		// // todo 设置更新用户信息
		// employee.setUpdateUser(1L);
		//
		
		
		employeeMapper.insert(employee);
		
	}
	
	@Override
	public List<Employee> findByName(String name) {
		
		return employeeMapper.findByName(name);
	}
	
	//用户更新
	@Override
	public void update(Employee employee) {
		
		// employee.setUpdateUser(EmployeeUtil.getNowUser(session).getId());
		// employee.setUpdateTime(new Date());
		
		employeeMapper.update(employee);
	}
	
	@Override
	public Employee findById(String id) {
		
		return employeeMapper.findById(id);
	}
}
